//
//  UITextField+appFont.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/30.
//

#import "UITextField+appFont.h"
#define CustomRegularFontName @"SFUIDisplay-Regular"
#define CustomBoldFontName @"SFUIDisplay-Bold"
#define CustomMediumFontName @"SFUIDisplay-Medium"
#define CustomLightFontName @"SFUIDisplay-Light"
#define CustomSemiboldFontName @"SFUIDisplay-Semibold"

@implementation UITextField (appFont)
+ (void)load {
    //方法交换应该被保证，在程序中只会执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //获得viewController的生命周期方法的selector
        SEL systemSel = @selector(willMoveToSuperview:);
        //自己实现的将要被交换的方法的selector
        SEL swizzSel = @selector(myWillMoveToSuperview:);
        //两个方法的Method
        Method systemMethod = class_getInstanceMethod([self class], systemSel);
        Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
        
        //首先动态添加方法，实现是被交换的方法，返回值表示添加成功还是失败
        BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
        if (isAdd) {
            //如果成功，说明类中不存在这个方法的实现
            //将被交换方法的实现替换到这个并不存在的实现
            class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
        } else {
            //否则，交换两个方法的实现
            method_exchangeImplementations(systemMethod, swizzMethod);
        }
        
    });
}

- (void)myWillMoveToSuperview:(UIView *)newSuperview {
    [self myWillMoveToSuperview:newSuperview];
    if (self) {
        NSString *name = [self.font fontName].lowercaseString;
        if ([name containsString:@"regular"]) {
            self.font  = [UIFont fontWithName:CustomRegularFontName size:self.font.pointSize];
        }else if ([name containsString:@"bold"]){
            self.font  = [UIFont fontWithName:CustomBoldFontName size:self.font.pointSize];
        }else if ([name containsString:@"medium"]){
            self.font  = [UIFont fontWithName:CustomMediumFontName size:self.font.pointSize];
        }else if ([name containsString:@"light"]){
            self.font  = [UIFont fontWithName:CustomLightFontName size:self.font.pointSize];
        }else if ([name containsString:@"semibold"]){
            self.font  = [UIFont fontWithName:CustomSemiboldFontName size:self.font.pointSize];
        }else{
            self.font  = [UIFont fontWithName:CustomRegularFontName size:self.font.pointSize];
        }
        
    }
}

@end
